import { useState } from "react";
import { FaSearch, FaBars } from "react-icons/fa";
import { useNavigate } from "react-router-dom";
import { userExitApi } from "../../http/module/User";

const Header = () => {
  const navigate = useNavigate();
  const [isLogin, setIsLogin] = useState(
    localStorage.getItem("isLogin") === "true"
  );

  const gotoLogin = () => {
    navigate("/login");
  };

  const handleLogout = () => {
    userExitApi()
      .then(() => {
        localStorage.setItem("isLogin", "false");
        localStorage.removeItem("token");
        setIsLogin(false);
        navigate("/");
      })
      .catch((error) => {
        console.error("Logout failed:", error);
      });
  };

  return (
    <header className="flex items-center justify-between p-4 bg-white shadow">
      <div className="flex items-center space-x-4">
        <FaBars className="text-xl cursor-pointer md:hidden" />
        <span className="text-2xl font-bold text-blue-500">
          ProgrammingQuestionPlatform
        </span>
      </div>
      <div className="flex items-center border rounded-lg px-3 py-1 w-1/2">
        <FaSearch className="text-gray-400" />
        <input
          type="text"
          placeholder="Search..."
          className="w-full px-2 py-1 outline-none"
        />
      </div>
      <button
        onClick={isLogin ? handleLogout : gotoLogin}
        className="bg-blue-500  text-white px-4 py-2 rounded hover:bg-blue-600 transition-colors"
      >
        {isLogin ? "Exit" : "Login"}
      </button>
    </header>
  );
};

export default Header;
